package com.example.fangwei.utilsapp.common_util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Random;


/**
 * 网络请求的工具类
 * Created by fangw on 2018/4/28.
 */

public class HttpUtil {
    private static final String TAG = HttpUtil.class.getSimpleName();
    private static final int connectTimeOut = 8000;
    private static final int readTimeOut = 8000;
    private static final String GET = "GET";
    private static final String POST = "POST";


    /**
     * 采用get方式请求网络数据
     * 通过inputStream获取响应数据
     * @param urlPath 请求地址
     * @return 服务器的响应结果(字符串)
     */
    public static String httpRequestByGet(String urlPath){

        HttpURLConnection connection = null;
        try{
            URL url = new URL(urlPath);
            connection  = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            connection.setRequestMethod(GET);
            connection.setDoInput(true);// 设置可以从服务器读数据，默认为 true 可不设

            int responseCode = connection.getResponseCode();
            if(200 == responseCode){//获取到服务器的响应
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                StringBuilder response = new StringBuilder();
                String line = "";
                while(null != (line = reader.readLine())){
                    response.append(line);
                }
                inputStream.close();
                reader.close();

                return response.toString();
            }

            if(302 == responseCode){//被重定向了
                String location = connection.getHeaderField("location");
                return httpRequestByGet(location);
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(null != connection){
                connection.disconnect();//关闭连接
            }
        }

        return null;
    }


    /**
     * 采用get方式请求网络数据
     * 通过ByteArrayOutputStream来获取响应内容
     * @param urlPath 请求地址
     * @return 服务器的响应结果
     */
    public static String httpRequestByGet2(String urlPath){
        HttpURLConnection connection = null;
        try{
            URL url = new URL(urlPath);
            connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            connection.setRequestMethod(GET);
            connection.setDoInput(true);// 设置可以从服务器读数据，默认为 true 可不设

            int responseCode = connection.getResponseCode();

            if(200 == responseCode){
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int length;
                while((length = inputStream.read(buffer)) != -1){
                    baos.write(buffer,0,length);
                }
                inputStream.close();
                baos.close();
                return baos.toString();
            }

            if(302 == responseCode){
                String location = connection.getHeaderField("location");
                return  httpRequestByGet2(location);
            }
        }catch(Exception e){

        }finally{
            if(null != connection){
                connection.disconnect();
            }
        }
        return null;
    }


    /**
     * 通过网络请求获取bitmap对象 展示图片
     * @param urlPath 图片的网络地址
     * @return bitmap 对象
     */
    public static Bitmap bitmapRequestByGet(String urlPath){
        HttpURLConnection connection = null;
        try{
            URL url = new URL(urlPath);
            connection  = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);
            connection.setRequestMethod(GET);
            connection.setDoInput(true);// 设置可以从服务器读数据，默认为 true 可不设

            int responseCode = connection.getResponseCode();

            if(200 == responseCode){
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int length;
                while((length = inputStream.read(buffer)) != -1){
                    baos.write(buffer,0,length);
                }
                inputStream.close();
                baos.close();
                return BitmapFactory.decodeByteArray(baos.toByteArray(),0,baos.size());
            }

            if(302 == responseCode){
                String location = connection.getHeaderField("location");
                return  bitmapRequestByGet(location);
            }
        }catch(Exception e){

        }finally{
            if(null != connection){
                connection.disconnect();
            }
        }
        return null;
    }


    /**
     * 采用post方式请求网络数据
     *
     * @param urlPath 请求路径
     * @param params 请求参数
     * @return 服务器的响应结果
     */
    public static String httpRequestByPost(String urlPath, Map<String,Object> params){
        StringBuilder result = new StringBuilder();

        HttpURLConnection connection = null;
        OutputStreamWriter writer = null;
        BufferedReader reader = null;

        try{
            URL url = new URL(urlPath);
            connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(POST);
            //post请求必须设置以下两项
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //设置连接超时时间和读取超时时间
            connection.setConnectTimeout(connectTimeOut);
            connection.setReadTimeout(readTimeOut);

            connection.setRequestProperty("Connection", "keep-alive");


            writer = new OutputStreamWriter(connection.getOutputStream());
            for(String key:params.keySet()){
                writer.write(key + "=" + params.get(key) + "&");
            }
            writer.flush();
            writer.close();

            int responseCode = connection.getResponseCode();
            if(200 == responseCode){
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String line;
                while ((line = reader.readLine()) != null){
                    result.append(line);
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            closeCloseable(writer);
            closeCloseable(reader);
            if(null != connection){
                connection.disconnect();
            }
        }

        return result.toString();

    }



    /**
     * 统一关闭Closeable对象的方法 减少冗余的代码
     * @param closeable 可关闭的Closeable对象
     */
    private  static void closeCloseable(Closeable closeable) {
        try {
            if (null != closeable) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "closeCloseable has been failed  == "+ e.getMessage() );
        }
    }


    /**
     *  在一个区间内产生随机整数数
      * @param min 区间最大值
     * @param max 区间最小值
     * @return
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
}
